import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { useState, useMemo } from "react";
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import { StockMoveApi } from "@/api/erp/stock/move";
import { message, Tabs } from "antd";
import { useTranslation } from "react-i18next";
import { BasicProTable, useProTable } from "@/components/ViewComponents/proTable";
import { Button } from "antd";
import { WarehouseApi } from "@/api/erp/stock/warehouse";
import { productApi } from "@/api/erp/drug/drug";
import { StockApi } from "@/api/erp/stock/stock";
const newAdd = (props: { register: Fn }) => {
	const en_vi = "drugStorage.inventoryManagement";
	const { t } = useTranslation();
	const [id, setId] = useState(0);
	let reload: Function;
	const [isUpdated, setIsUpdated] = useState(false);
	const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(props.register, data => {
		reload = data.reload;
		resetFields();
		setDrawerProps({ confirmLoading: true });
		setIsUpdated(!!data?.isUpdated);
		setId(data.record?.id);
		data.isUpdated
			? setFieldsValue(data.record?.items)
			: setFieldsValue([
					{
						key: new Date().getTime(),
						fromWhsId: undefined,
						toWhsId: undefined,
						productId: undefined,
						productBarCode: undefined,
						productUnitName: undefined,
						stockCount: undefined,
						remark: undefined,
						count: 1,
						productPrice: undefined
					}
			  ]);
		setFieldsValueFn({
			...data.record
		});
		setDrawerProps({ confirmLoading: false });
	});
	const getTitle = useMemo(() => {
		return isUpdated ? t(`${en_vi}.warehouseInformation.editWarehouseInfo`) : t(`${en_vi}.warehouseInformation.addWarehouseInfo`);
	}, [isUpdated]);
	const formItems: FormSchema[] = [
		{
			label: t(`${en_vi}.inventoryTransfer.mvId`),
			component: "Input",
			field: "mvId",
			componentProps: {
				disabled: true,
				placeholder: t("drugStorage.automaticallySaving")
			}
		},
		{
			label: t(`${en_vi}.inventoryTransfer.mvTime`),
			component: "DatePicker",
			field: "mvTime"
		},
		{
			label: t(`${en_vi}.warehouseInformation.remark`),
			component: "InputTextArea",
			field: "remark"
		},

		{
			label: t("drugStorage.attachment"),
			component: "FileUpload",
			field: "fileUrl",
			componentProps: {
				// fileType: "image",
				maxCount: 1
			}
		}
	];
	const [formTop, { validateFields, setFieldsValue: setFieldsValueFn, resetFields }] = useForm({
		schemas: formItems,
		labelWidth: 150,
		baseColProps: { span: 12 }
	});
	const dataSource = [
		{
			key: new Date().getTime(),
			fromWhsId: undefined,
			toWhsId: undefined,
			productId: undefined,
			productBarCode: undefined,
			productUnitName: undefined,
			stockCount: undefined,
			remark: undefined,
			count: 1,
			productPrice: undefined
		}
	];
	const defaultColumns = [
		{
			title: t("felix_ui.sq_numb"),
			// dataIndex: "sq_numb",
			render: (text, record, index) => index * 1 + 1 // 设置序号
		},
		{
			title: t(`${en_vi}.inventoryTransfer.fromWhsId`),
			dataIndex: "fromWhsId",
			editable: true,
			// width: "20%",
			type: "ApiSelect",
			componentProps: {
				api: WarehouseApi.getWarehouseSimpleList,
				labelField: "name",
				valueField: "whsId",
				onChange: () => {
					onChangeWarehouse();
				}
			}
		},
		{
			title: t(`${en_vi}.inventoryTransfer.toWhsId`),
			dataIndex: "toWhsId",
			editable: true,
			// width: "20%",
			type: "ApiSelect",
			componentProps: {
				api: WarehouseApi.getWarehouseSimpleList,
				labelField: "name",
				valueField: "whsId"
			}
		},
		{
			title: t("drugStorage.productName"),
			dataIndex: "productId",
			editable: true,
			// width: "20%",
			type: "ApiSelect",
			componentProps: {
				api: productApi.getproductSimpleList,
				labelField: "productName",
				valueField: "productId",
				immediate: false,
				params: {
					bizType: "2"
				},
				onChange: () => {
					onChangeProduct();
				}
			}
		},
		{
			title: t(`${en_vi}.inventoryCount.stockCount`),
			dataIndex: "stockCount"
		},
		{
			title: t(`${en_vi}.inventoryCount.productBarCode`),
			dataIndex: "productBarCode"
		},
		{
			title: t("drugStorage.inventoryManagement.drugInventory.unitName"),
			dataIndex: "productUnitName"
		},
		{
			title: t("felix_ui.remark"),
			dataIndex: "remark",
			editable: true
		},
		{
			title: t("drugStorage.inventoryManagement.drugInventory.count"),
			dataIndex: "count",
			fixed: "right"
		},
		{
			title: t("drugStorage.inventoryManagement.drugInventory.salePrice"),
			dataIndex: "productPrice",
			editable: true,
			type: "InputNumber",
			fixed: "right"
		},
		{
			title: t("felix_ui.action"),
			fixed: "right",
			width: 100,
			render: (_, obj) => {
				return <Button onClick={onDelete(obj)}>{t("felix_ui.delete")}</Button>;
			}
		}
	];
	const [proTable, { submit, handleAdd, handleDelete, setFieldsValue, setRowData, getRowData }] = useProTable({
		defaultColumns,
		dataSource
	});
	const onAdd = () => {
		handleAdd({
			key: new Date().getTime(),
			fromWhsId: undefined,
			toWhsId: undefined,
			productId: undefined,
			productBarCode: undefined,
			productUnitName: undefined,
			stockCount: undefined,
			remark: undefined,
			count: 1,
			productPrice: undefined
		});
	};
	const onDelete = obj => () => {
		handleDelete(obj.key);
	};
	const handleSubmit = async () => {
		const values = await validateFields();
		const items = await submit();
		values.mvTime = new Date(values.mvTime).getTime();
		values.items = items;
		values.totalCount = 0;
		values.totalPrice = 0;
		items.map((item: any) => {
			values.totalCount += item.count / 1;
			values.totalPrice += item.productPrice / 1;
		});
		let res;
		if (isUpdated) {
			values.id = id;
			res = await StockMoveApi.updateStockMove(values);
		} else {
			res = await StockMoveApi.createStockMove(values);
		}
		if (!res) {
			message.error(t("viewComponents.patientInformation.additionFailed"));
			return;
		}
		message.success(t("viewComponents.patientInformation.successfullyAdded"));
		closeDrawer();
		reload();
	};
	/** 处理仓库变更 */
	const onChangeWarehouse = () => {
		const row = getRowData();
		// 加载库存
		setStockCount(row);
	};

	/** 处理产品变更 */
	const onChangeProduct = async () => {
		const row = getRowData();
		const productList = await productApi.getproductSimpleList({ bizType: "2" });
		const product = productList.find((item: any) => item.productId === row.productId);
		if (product) {
			setRowData({
				productUnitName: product.productUnitName,
				productBarCode: product.barCode,
				productPrice: product.minPrice
			});
		}
		// 加载库存
		setStockCount(row);
	};
	/** 加载库存 */
	const setStockCount = async (row: any) => {
		if (!row.productId || !row.fromWhsId) {
			return;
		}
		const stock = await StockApi.getStock2(row.productId, row.fromWhsId);
		setRowData({
			stockCount: stock.count ? stock.count : 0
		});
	};
	return (
		<BasicDrawer size="large" {...props} title={getTitle} register={registerDrawer} ok={handleSubmit} showFooter={true}>
			<Tabs>
				<Tabs.TabPane tab={t("drugStorage.inventorydrugs")}>
					<BasicForm register={formTop}></BasicForm>
					<Button onClick={onAdd}> {t("felix_ui.add")}</Button>
					<div style={{ width: "100%", overflow: "auto" }}>
						<BasicProTable register={proTable}></BasicProTable>
					</div>
				</Tabs.TabPane>
			</Tabs>
		</BasicDrawer>
	);
};
export default newAdd;
